<template>
  <a-modal
      title="添加共享范围"
      :width="700"
      :visible="addVisible"
      :confirm-loading="confirmLoading"
      @ok="handleAddOk"
      @cancel="handleAddCancel"
      :maskClosable="false"
    >
      <a-form-model ref="form" :model="model" :rules="validatorRules" style="width: 600px">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="对象类型：" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-radio-group
                v-model="model.objectType"
                name="radioGroup"
                :default-value="1"
                @change="handleObjectChange"
              >
                <a-radio :value="1"> 私有组 </a-radio>
                <a-radio :value="2"> 发送人员 </a-radio>
                <a-radio :value="3"> 组织架构 </a-radio>
                 <a-radio :value="4"> 所有人公开 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="对象名称" :label-col="labelCol" :wrapper-col="wrapperCol" prop="selectObject">
              <a-select
                v-if="model.objectType < 3"
                ref="selectRef"
                v-model="model.selectObject"
                mode="multiple"
                placeholder="请输入对象名称"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? '找不到记录' : null"
                :labelInValue="true"
                @search="fetchObj"
                @change="selectObjectChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="d in objData" :key="d.value" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
              <a-tree-select
                      v-if="model.objectType === 3"
                      v-model="model.selectObject"
                      :tree-data="treeData"
                      tree-checkable
                      :showCheckedStrategy="SHOW_ALL"
                      show-search
                      :replaceFields="{ children: 'children', title: 'title', key: 'id', value: 'id' }"
                      :maxTagCount="3"
                      @search="searchDep"
                      search-placeholder="请选择组织架构"
                      :labelInValue="true"
              >
              </a-tree-select>

              <a-select
                v-if="model.objectType === 4"
                ref="selectRef"
                v-model="model.selectObject"
                :default-value="['公开']"
                :disabled="true"
                mode="multiple"
                placeholder="请输入对象名称"
                style="width: 100%"
                :labelInValue="true"
              >
               
                  <a-select-option v-for="d in openObjData" :key="d.value" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="权限" :label-col="labelCol" :wrapper-col="wrapperCol" prop="authority">
              <a-select v-model="model.authority" mode="multiple" placeholder="请选择权限">
                <a-select-option
                  v-for="option in authorityOptions"
                  :key="'auth' + option.value"
                  :value="option.value"
                  :defaultValue="[1]"
                  :disabled="option.disabled"
                  >{{ option.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
</template>

<script>
import { postAction, getAction } from '@/api/manage';
import { TreeSelect } from 'ant-design-vue';
const SHOW_ALL = TreeSelect.SHOW_ALL;
export default {
  name: 'FileRangeAdd',
  components: {
  },    

  props: {
      visible:{
          type:Boolean,
          
      },
      saveData:{
          type:Array,
          default:[]
      },
      fileType:{
        type:Number,
        default: null
      }
  },
  data() {
    return {
      SHOW_ALL,
        authorityOptions: [
        { value: '1', label: '查阅', disabled: false },
        { value: '2', label: '编辑', disabled: false },
        { value: '3', label: '下载', disabled: false },
        { value: '4', label: '可废除', disabled: false },
        { value: '5', label: '一级发布', disabled: true }
      ],

         model: { 'objectType': 1, 'client': '海芯' ,'objectId':[]},
      validatorRules: {
        authority: [{ required: true, message: '请选择权限' }],
        objectId: [{ required: true, message: '请输入选择' }],
      },
       labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      objData: [],
      openObjData:[{ label: '公开', value: '公开',key:'公开' }],
      fetching: false,
      treeData: [],
      url: {
        list: '/lib/hteFileClassRange/list',
        getUserList: '/lib/hteFileClass/getUserList',
        getGroupList: '/lib/hteLibraryGroup/groupList',
        getClassAuthority: '/lib/hteFileClass/getClassAuthority',
        getDeptTree: '/lib/hteDict/getDeptTree',
       
      },
      addVisible: false,
      confirmLoading: false,
     
     
    };
  },
   watch:{
      visible:function(val){
          
        this.addVisible = val
        if(val){
           
            this.handleOpen();
        }
        
      }

  },
  created(){
      
    
  },
  methods: {
      getDeptTree(){
          const that = this
          getAction(this.url.getDeptTree, {}).then(res => {
            if (res.success) {
                that.treeData = res.result;
            } else {
                that.$message.error('获取组织架构数据错误');
            }
            });
      },
      searchDep(keyword){
        const that = this
          getAction(this.url.getDeptTree, {keyword}).then(res => {
            if (res.success) {
                that.treeData = res.result;
            } else {
                that.$message.error('获取组织架构数据错误');
            }
            });
      },
      handleOpen(){
           
            this.$forceUpdate()
          this.model = { 'objectType': 1, 'client': '海芯' ,'objectId':[]}
      
         
        this.getDeptTree();
        this.getClassAuthority();
      },
      getClassAuthority(){
        if (this.fileType) {
          getAction(this.url.getClassAuthority, { id: this.fileType }).then(res => {
            if (res.success) {
              this.authorityOptions = res.result;
            }
          });
        }
      },
       handleAddOk() {
           let that =this;
          
        this.$refs.form.validate((valid) => {
            if (valid) {

            let objectId = '';
            let objectName = '';
            
           
            that.model.selectObject.forEach(row => {
                
                 if(that.model.objectType == 3){
                    objectId += row.value + ',';
                }else{
                  objectId += row.key + ',';      
                }
                objectName += row.label + ',';
            });
          that.$set(that.model, 'objectId', objectId.substr(0, objectId.length - 1));
          that.$set(that.model, 'objectName', objectName.substr(0, objectName.length - 1));
          that.$set(that.model, 'authority', that.model.authority + '');
         
            for (let index = 0; index < this.saveData.length; index++) {
                const element = this.saveData[index];
                if( this.model.objectId.indexOf(element.objectId) > -1 && element.objectType == this.model.objectType  ){
                    that.$message.error(`${element.objectName}共享范围已存在！`);
                    
                     that.$set(that.model, 'authority',  []);
                    valid = false
                    return
                }
            }
        if(valid){
            this.$emit('handleAddOk',this.model )
            this.addVisible = false
            
        }
          
        }
      })
    },
    handleAddCancel() {
        this.$emit('handleAddCancel' )
    
    },
     handleObjectChange(val) {
      this.$set(this.model, 'objectId', []);
      this.$set(this.model, 'authority', []);
      this.$set(this.model, 'selectObject', []);
      //公开类型处理
      debugger
      if( this.model.objectType === 4){
        this.$set(this.model, 'selectObject', this.openObjData);
      }
      this.objData = [];
      const forwardOption = this.authorityOptions.find(value => value.value === '5');
      if (forwardOption && this.model.objectType === 1) {
        this.$set(forwardOption, 'disabled', true);
      } else if (forwardOption) {
        this.$set(forwardOption, 'disabled', false);
      }
    },
    fetchObj(val) {
      this.objData = [];
      this.fetching = true;
      let url = this.url.getGroupList;
      if (this.model.objectType === 2) {
        url = this.url.getUserList;
      }
      getAction(url, { name: val }).then(res => {
        if (res.success) {
          this.objData = res.result;
          if (res.result.length > 0) {
            this.fetching = false;
            if (this.model.objectType == 2) {
              res.result.forEach(it => {
                this.objData.push({ label: it.realname, value: it.username });
              });
            } else {
              res.result.forEach(it => {
                this.objData.push({ label: it.name, value: it.id });
              });
            }
          }
        }
      });
    },
    selectObjectChange() {
      this.$refs.selectRef.blur();
    }
  },
  computed:{
  },
  filters: {
  },
 
  mounted(){

  }
 }
</script>

<style scoped>

</style>
